package com.springsecurity.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.*;

@Component
public class JWTLogoutCache {

    // 使用ConcurrentHashMap来存储缓存项，保证线程安全
    private ConcurrentHashMap<String, Long> cacheMap = new ConcurrentHashMap<String, Long>();
    // 调度器用于清理过期缓存项
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // 构造方法，初始化调度器以清理过期缓存
    public JWTLogoutCache() {
        scheduler.scheduleAtFixedRate(this::cleanUp, 1, 1, TimeUnit.SECONDS); // 每秒执行一次清理任务
    }


    // 添加缓存项
    public void put(String jwt, long expiryDurationMillis) {

        cacheMap.put(jwt, System.currentTimeMillis() + expiryDurationMillis);
    }

    // 判断缓存的jwt是否存在黑名单中
    public boolean contains(String jwt) {
        if (!cacheMap.containsKey(jwt)) {
            return false;
        }
        Long ttl = cacheMap.get(jwt);
        long currentTimeMillis = System.currentTimeMillis();
        if (ttl < currentTimeMillis) { // 缓存过期
            cacheMap.remove(jwt);
            return false;
        }
        return true;
    }

    // 清理过期的缓存项
    private void cleanUp() {
        long currentTime = System.currentTimeMillis();

        for (Map.Entry<String, Long> cacheMapEntry : cacheMap.entrySet()) {
            if (cacheMapEntry.getValue() < currentTime) { // 检查是否过期
                cacheMap.remove(cacheMapEntry.getKey()); // 过期则移除
            }
        }
    }

//    public static void main(String[] args) throws InterruptedException {
//        JWTLogoutCache jwtLogoutCache = new JWTLogoutCache();
//        String jwt = "sdsssss";
//        jwtLogoutCache.put(jwt, 5 * 1000L);
//
//        Thread.sleep(3000);
//        System.out.println(jwtLogoutCache.get(jwt));
//        Thread.sleep(3000);
//        System.out.println(jwtLogoutCache.get(jwt));
//
//    }
}
